import { observable, extendObservable, action, toJS } from 'mobx'
import { topicSchema } from '../utils/variable'
import { get } from '../utils/http'

const createTopic = data => {
  return Object.assign({}, topicSchema, data)
}

export class Topic {
  constructor(data) {
    extendObservable(this, data)
  }

  @observable syncing = false
}

export class TopicStore {
  @observable topics

  @observable syncing

  @observable tab

  constructor({ topics = [], syncing = false, tab = null } = {}) {
    this.syncing = syncing
    this.topics = topics.map(topic => new Topic(createTopic(topic)))
    this.tab = tab
  }

  @action fetchTopics(tab) {
    return new Promise((resolve, reject) => {
      if (tab === this.tab && this.topics.length > 0) {
        resolve()
      } else {
        this.topics = []
        this.syncing = true
        this.tab = tab

        get('/topics', {
          mdrender: false,
          tab,
        })
          .then(res => {
            if (res.success) {
              const topics = res.data.map(topic => {
                return new Topic(createTopic(topic))
              })
              this.topics = topics
              this.syncing = false
              resolve()
            } else {
              this.syncing = false
              reject()
            }
          })
          .catch(err => {
            reject(err)
          })
      }
    })
  }

  toJson() {
    return {
      topics: toJS(this.topic),
      syncing: toJS(this.syncing),
      tab: this.tab,
    }
  }
}

export default TopicStore
